package com.sanhe.a448.activity.work

import android.os.Bundle
import android.view.View
import com.google.gson.Gson
import com.menu.app.MyApp
import com.menu.app.activity.BaseBoardActivity
import com.menu.app.db.CusUsageDao
import com.menu.app.db.CustomDao
import com.menu.app.db.DocDao
import com.menu.app.db.TreatDao
import com.menu.app.db.bean.Treat
import com.menu.app.http.req.ReportReq
import com.menu.app.util.Utils
import com.sanhe.a448.App
import com.sanhe.a448.R
import com.sanhe.a448.bean.WorkParam
import com.sanhe.a448.databinding.ActivityWorkBinding
import com.sanhe.a448.event.AlertEvent
import com.sanhe.a448.event.BigEnergyEvent
import com.sanhe.a448.event.Event
import com.sanhe.a448.event.ModeEvent
import com.sanhe.a448.event.MsgEvent
import com.sanhe.a448.event.PowerEvent
import com.sanhe.a448.event.PowerProgress
import com.sanhe.a448.event.SmallEnergyEvent
import com.sanhe.a448.event.StartEvent
import com.sanhe.a448.event.StateDeep
import com.sanhe.a448.event.StateFour
import com.sanhe.a448.event.StateOne
import com.sanhe.a448.event.StateSurface
import com.sanhe.a448.event.StateTwo
import com.sanhe.a448.event.TimeEvent
import com.sanhe.a448.event.TimeProgress
import com.sanhe.a448.event.TipEvent
import com.sanhe.a448.utils.Const
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class WorkActivity : BaseWorkActivity() {

    lateinit var binding: ActivityWorkBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityWorkBinding.inflate(layoutInflater)
        setContentView(binding!!.root)
        binding!!.back.setOnClickListener { v: View? ->
            Const.sendTouchEvent(0x83, 0x1e, 1, 1, 0xa)
            if (Event.start.isStarted) {
                return@setOnClickListener
            }
            h.postDelayed({ finish() }, 500)
        }
        binding.time.bar.isEnabled = false
        binding.power.bar.isEnabled = false

        binding!!.one.setOnClickListener { v: View? ->
            Const.sendTouchEvent(
                0x82,
                0x1e,
                0xb6,
                0,
                0xb7
            )
        }
        binding!!.two.setOnClickListener { v: View? ->
            Const.sendTouchEvent(
                0x82,
                0x1e,
                0xb6,
                0,
                0xb8
            )
        }
        binding!!.four.setOnClickListener { v: View? ->
            Const.sendTouchEvent(
                0x82,
                0x1e,
                0xb6,
                0,
                0xb6
            )
        }

        binding!!.surface.setOnClickListener { v: View? ->
            Const.sendTouchEvent(
                0x82,
                0x1e,
                0xb1,
                0,
                0xb1
            )
        }
        binding!!.deep.setOnClickListener { v: View? ->
            Const.sendTouchEvent(
                0x82,
                0x1e,
                0xb1,
                0,
                0xb2
            )
        }

        binding!!.power.icon.setImageResource(R.mipmap.power_icon)
        binding!!.power.tv.setText(R.string.energy)

        setTouch(
            binding!!.time.left
        ) { Const.sendTouchEvent(0x83, 0x1e, 0x11, 0, 1) }
        setTouch(
            binding!!.time.right
        ) { Const.sendTouchEvent(0x83, 0x1e, 0x10, 0, 1) }
        setTouch(
            binding!!.power.left
        ) { Const.sendTouchEvent(0x83, 0x1e, 0x18, 0, 1) }
        setTouch(
            binding!!.power.right
        ) { Const.sendTouchEvent(0x83, 0x1e, 0x17, 0, 1) }
        binding!!.start.setOnClickListener { v: View? ->
            if (!checkRentTime(this) && !Event.start.isStarted) {
                return@setOnClickListener
            }
            Const.sendTouchEvent(0x83, 0x1e, 0x1a, 0x1c, 0x1a)
            if (Const.jump) {
                if (Event.start.isStarted) {
                    Event.start.postValue(4)
                } else {
                    Event.start.postValue(0)
                }
            }
        }

        onMessageEvent(Event.mode)
        onMessageEvent(Event.stateOne)
        onMessageEvent(Event.stateTwo)
        onMessageEvent(Event.stateFour)
        onMessageEvent(Event.stateSurface)
        onMessageEvent(Event.stateDeep)
        onMessageEvent(Event.bigEnergyEvent)
        onMessageEvent(Event.smallEnergyEvent)
        onMessageEvent(Event.time)
        onMessageEvent(Event.power)
        onMessageEvent(Event.timeProgress)
        onMessageEvent(Event.powerProgress)
        onMessageEvent(Event.alert)
        onMessageEvent(Event.start)
        onMessageEvent(Event.msg)
        onMessageEvent(Event.tip)

        val old = App.getApp().workParam
        App.getApp().workParam = null
        if (old != null) {
            GlobalScope.launch { setParam(old) }
        }
    }

    override fun getBackgroundRes(): Int {
        return R.mipmap.work_bg
    }

    private suspend fun setParam(param: WorkParam) {
        h.post { showLoading() }
        if (param.mode == 1 || param.mode == 11) {
            binding.deep.performClick()
            delay(200)
        }
        if (param.mode == 10 || param.mode == 11) {
            binding.surface.performClick()
            delay(200)
        }
        var last = -1
        var times = 0;
        while (true) {
            if (Event.time.time != param.time) {
                if (last != Event.time.time) {
                    last = Event.time.time
                    times = 0
                } else {
                    if (++times >= 5) {
                        break;
                    }
                }
                if (Event.time.time > param.time) {
                    Const.sendTouchEvent(0x83, 0x1e, 0x11, 0, 1)
                } else {
                    Const.sendTouchEvent(0x83, 0x1e, 0x10, 0, 1)
                }
                delay(200)
            } else {
                break
            }
        }
        last = -1
        times = 0
        while (true) {
            if (Event.power.power != param.energy) {
                if (last != Event.power.power) {
                    last = Event.power.power
                    times = 0
                } else {
                    if (++times >= 5) {
                        break;
                    }
                }
                if (Event.power.power > param.energy) {
                    Const.sendTouchEvent(0x83, 0x1e, 0x18, 0, 1)
                } else {
                    Const.sendTouchEvent(0x83, 0x1e, 0x17, 0, 1)
                }
                delay(200)
            } else {
                break
            }
        }
        h.post { hideLoading() }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: ModeEvent) {
        when (event.value) {
            1 -> {
                binding!!.title.text = "RET"
                binding!!.head.setImageResource(R.mipmap.h5)
            }

            2 -> {
                binding!!.title.text = "CET"
                binding!!.head.setImageResource(R.mipmap.h6)
            }

            3 -> {
                binding!!.title.text = "HSP"
                binding!!.head.setImageResource(R.mipmap.h7)
            }

            4 -> {
                binding!!.title.text = getString(R.string.indi)
                binding!!.head.setImageResource(R.mipmap.h8)
                binding!!.tv.visibility = View.INVISIBLE
                binding!!.linear1.visibility = View.INVISIBLE
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: TipEvent) {
        val s = event.toString()
        binding.tip.text = s
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MsgEvent) {
        binding!!.msg.text = event.toString()
    }

    private fun record(point: Long, time: Long) {
        if (BaseBoardActivity.custom != null) {
            BaseBoardActivity.custom.num += point
            CustomDao().updateCount(BaseBoardActivity.custom, null)
        }
        try {
            insert(point, time)
        } catch (e: Throwable) {
            e.printStackTrace()
        }
        if (MyApp.getApp().doc != null) {
            MyApp.getApp().doc.num += point
            DocDao().updateCount(MyApp.getApp().doc, null)
        }
    }

    var dao: CusUsageDao? = null

    private fun insert(point: Long, time: Long) {
        val usr = BaseBoardActivity.custom
        if (dao == null) {
            dao = CusUsageDao()
        }
        val tmp = buildParam()
        val gson = Gson()
        dao!!.insert(
            point, usr, tmp.workType, gson.toJson(tmp)
        ) { bo, msg, result ->
            if (bo) {
                ReportReq(
                    buildReportParam(tmp),
                    if (usr == null) "" else usr.serverId,
                    Const.REPORT
                ).req { success, bean ->
                    if (success && bean != null && bean.isValid) {
                        dao!!.updateFlag((result as Long), null)
                    }
                }
            }
        }
    }

    private fun buildReportParam(param: WorkParam): Map<*, *> {
        val gson = Utils.getGson()
        val param: Map<*, *> = gson.fromJson<java.util.HashMap<*, *>>(
            gson.toJson(param),
            java.util.HashMap::class.java
        )
        return param
    }

    var treat: Treat? = null
    var started: Boolean = false
    var startTime: Long = 0
    var workTime: Int = 0

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: StartEvent) {
        if (event.isStarted) {
            binding!!.start.setImageResource(R.mipmap.start_press)
        } else {
            binding!!.start.setImageResource(R.mipmap.start_normal)
        }
        if (event.isStarted) {
            if (started) {
                return
            }
            started = true
            startTime = System.currentTimeMillis()
            workTime = Event.time.time
            if (MyApp.getApp().doc != null) {
                treat = Treat()
                treat!!.docId = MyApp.getApp().doc.id
                if (BaseBoardActivity.custom != null) {
                    treat!!.cusId = BaseBoardActivity.custom.id
                }
                treat!!.start = System.currentTimeMillis()
                TreatDao().insert(treat) { bo, msg, result ->
                    if (bo) {
                        treat = result as Treat
                    }
                }
            }
        } else {
            if (started) {
                if (treat != null && treat!!.id != -1L && treat!!.start > 0) {
                    treat!!.end = System.currentTimeMillis()
                    TreatDao().updateEnd(treat, null)
                }
                treat = null
                record(1, System.currentTimeMillis() - startTime)
                started = false
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: AlertEvent) {
        if (event.value == 1) {
            binding.alert.visibility = View.VISIBLE
        } else {
            binding.alert.visibility = View.GONE
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: StateOne) {
        if (event.value == 0) {
            binding!!.one.isSelected = false
        } else if (event.value == 1) {
            binding!!.one.isSelected = true
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: StateTwo) {
        if (event.value == 0) {
            binding!!.two.isSelected = false
        } else if (event.value == 1) {
            binding!!.two.isSelected = true
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: StateFour) {
        if (event.value == 0) {
            binding!!.four.isSelected = false
        } else if (event.value == 1) {
            binding!!.four.isSelected = true
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: StateSurface) {
        binding!!.surface.isSelected = event.value <= 3
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: StateDeep) {
        binding!!.deep.isSelected = event.value <= 3
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: BigEnergyEvent) {
        binding!!.energy.text = event.toString()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: SmallEnergyEvent) {
        binding!!.energy2.text = event.toString()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: TimeEvent) {
        binding!!.time.number.text = event.toString()
        binding.time.bar.progress = event.time
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: PowerEvent) {
        binding!!.power.number.text = event.toString()
        binding.power.bar.progress = event.power
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: TimeProgress) {
//        binding!!.time.bar.progress = event.value
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: PowerProgress) {
//        binding!!.power.bar.progress = event.value
    }

    private fun buildParam(): WorkParam {
        val param = WorkParam()
        if (binding!!.surface.isSelected) {
            if (binding!!.deep.isSelected) {
                param.mode = 11
            } else {
                param.mode = 10
            }
        } else {
            if (binding!!.deep.isSelected) {
                param.mode = 1
            } else {
                param.mode = 0
            }
        }
        param.time = workTime
        param.energy = Event.power.power
        param.workType = ModeActivity.mode
        return param
    }
}
